import { defineStore } from 'pinia'
import { useRequest } from "@usehook"
import { decryption } from '@/utils/tools'
import router from '@/router'

const useUserStore = defineStore("userInfo", {
    state: () => ({
        token: "",
        username: "",
        role: "",
        sequence: "",
        point: 0,
        apiToken: "",
        bindWx: false,
        registerTime: "",
        mail: "",
        mobile: "",
        nickname: "",
        payCount: 0,
        lastSignDate: "",
        avatar: ""
    }),
    getters: {
        getUserInfo: state => ({
            token: state.token ? decryption(state.token) : "",
            username: state.username ? decryption(state.username) : "",
            role: state.role ? decryption(state.role) : "",
            sequence: state.sequence ? decryption(state.sequence) : "",
            point: state.point,
            apiToken: state.apiToken,
            bindWx: state.bindWx,
            registerTime: state.registerTime,
            mail: state.mail,
            mobile: state.mobile,
            nickname: state.nickname,
            payCount: state.payCount,
            lastSignDate: state.lastSignDate,
            avatar: state.avatar
        }),
        islogin: state => !!state.token && !!state.sequence,
    },
    actions: {
        login(info) {
            // 确保info对象具有期望的属性
            if (!info || typeof info !== 'object' || !info.token || !info.username || !info.role || !info.sequence) {
                console.error('Invalid info object')
                return // 或者抛出一个错误
            }

            // 尝试更新信息，增加异常处理
            try {
                this.$patch((state) => {
                    // 使用解构赋值简化代码
                    const { token, username, role, sequence } = info
                    // 你可以在这里添加更复杂的数据验证逻辑
                    // 例如检查token的格式，username是否包含非法字符等

                    // 更新状态
                    state.token = token
                    state.username = username
                    state.role = role
                    state.sequence = sequence
                })
            } catch (error) {
                console.error('Failed to set user info:', error)
            }
        },
        updateUserInfo(info) {
            // 尝试更新信息，增加异常处理
            try {
                this.$patch((state) => {
                    // 使用解构赋值简化代码
                    const { point, api, bind_wx, crt_time, mail, mobile, nickname, pay_count, last_sign_date, avatar } = info
                    // 你可以在这里添加更复杂的数据验证逻辑
                    // 例如检查token的格式，username是否包含非法字符等

                    // 更新状态
                    if (point) state.point = point
                    if (api) state.apiToken = api
                    if (bind_wx) state.bindWx = bind_wx
                    if (crt_time) state.registerTime = crt_time
                    if (mail) state.mail = mail
                    if (mobile) state.mobile = mobile
                    if (nickname) state.nickname = nickname
                    if (pay_count) state.payCount = pay_count
                    if (last_sign_date) state.lastSignDate = last_sign_date
                    if (avatar) state.avatar = avatar
                })
            } catch (error) {
                console.error('Failed to update user info:', error)
            }
        },
        logout() {
            this.$patch((state) => {
                router.replace("/")
                // 更新状态
                useRequest({ url: "/logout", method: "post", token: decryption(state.token) }).then(res => {
                    console.log(res)
                })
                state.token = ""
                state.username = ""
                state.role = ""
                state.sequence = ""
                state.point = 0
                state.apiToken = ""
                state.bindWx = false
                state.registerTime = ""
                state.mail = ""
                state.mobile = ""
                state.nickname = ""
                state.payCount = 0
            })
        }
    },
    persist: {
        enabled: true,
        key: "userInfo",
        paths: ["role", "sequence", "username", "token"],
        storage: localStorage
    }
})

export default useUserStore